package com.ljkj.cordial.chat.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;

import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.crypto.DES;
import com.lanjiu.lib.utils.crypto.MD5;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.dao.UserTableBean;
import com.ljkj.cordial.chat.ui.AppEventActivity;
import com.ljkj.cordial.chat.ui.views.ForgetPasswordView;
import com.ljkj.cordial.chat.widget.DownTimeTextView;
import com.ljkj.cordial.chat.widget.RectButtonHintDialog;
import com.nic.view.util.JToast;
import com.nic.view.util.ValidateUtils;
import com.nic.view.widget.ContainsEmojiEditText;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 忘记密码
 */
public class ForgetPasswordActivity extends AppEventActivity<ForgetPasswordView> implements ForgetPasswordView.ForgetPassCallback {


    @BindView(R.id.et_password_again)
    ContainsEmojiEditText etPasswordAgain;
    @BindView(R.id.et_phone)
    ContainsEmojiEditText etPhone;
    @BindView(R.id.et_account)
    ContainsEmojiEditText etAccount;
    @BindView(R.id.et_captcha)
    ContainsEmojiEditText etCaptcha;
    @BindView(R.id.et_password)
    ContainsEmojiEditText etPassword;
    @BindView(R.id.cb_isOpen)
    CheckBox cbIsOpen;
    @BindView(R.id.cb_isOpen2)
    CheckBox cbIsOpen2;
    @BindView(R.id.tv_captcha)
    DownTimeTextView tvCaptcha;
    @BindView(R.id.ll_one_step)
    LinearLayout llOneStep;
    @BindView(R.id.ll_two_step)
    LinearLayout llTwoStep;
    @BindView(R.id.ll_account)
    LinearLayout llAccount;

    private int type;
    private static String NEXT_STEP = "下一步";
    private static String COMPLETE = "完成";
    private String mUserId;

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_forget_password;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        type = getIntent().getIntExtra(Canstants.KEY_REGISTER_OR_FIND_PSD, Canstants.STATE_REGISTER);
        if (Canstants.STATE_REGISTER == type) {
            getToolbar().setTitle("忘记密码");
//            llAccount.setVisibility(View.GONE);
            getToolbarRightTv().setText(NEXT_STEP);
        } else {
            etAccount.setEnabled(false);
            etAccount.setText("" + ChatApp.getInstance().getUserId());
            llOneStep.setVisibility(View.GONE);
            llTwoStep.setVisibility(View.VISIBLE);
            getToolbarRightTv().setText(COMPLETE);
            getToolbar().setTitle("重置密码");

        }
        getToolbarRightTv().setVisibility(View.VISIBLE);
        getToolbarRightTv().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Canstants.STATE_REGISTER == type) {
                    if (TextUtils.isEmpty(etAccount.getText())) {
                        etAccount.setError("不能为空");
                        return;
                    } else if (TextUtils.isEmpty(etPhone.getText())) {
                        etPhone.setError("不能为空");
                        return;
                    } else if (!ValidateUtils.Mobile(etPhone.getText().toString())) {
                        etPhone.setError("不是有效号码");
                        return;
                    }
                }
                if (COMPLETE.equals(getToolbarRightTv().getText().toString())) {
                    if (TextUtils.isEmpty(etPassword.getText())) {
                        etPassword.setError("不能为空");
                        return;
                    } else if (etPassword.getText().length() < 6) {
                        etPassword.setError("密码不能小于6位");
                        return;
                    }else if (TextUtils.isEmpty(etPasswordAgain.getText())) {
                        etPasswordAgain.setError("不能为空");
                        return;
                    } else if (!etPassword.getText().toString().equals(etPasswordAgain.getText().toString())) {
                        etPasswordAgain.setError("密码不一致");
                        return;
                    }
                    if (Canstants.STATE_REGISTER != type)
                        mUserId = UserPreferences.getUserId();
                    String obviousPassword = etPassword.getText().toString();
                    if ("123456".equals(obviousPassword)) {
                        new RectButtonHintDialog(ForgetPasswordActivity.this)
                                .setTitle("账号安全")
                                .setContent("您的密码过于简单，建议您修改密码")
                                .setLeftSubmit("确认修改", left -> {
                                    String password = DES.encode(obviousPassword);
                                    obtainView().doReset(mUserId, password);
                                })
                                .setRightSubmit("重设密码", null)
                                .show();
                    } else {
                        String password = DES.encode(obviousPassword);
                        obtainView().doReset(mUserId, password);
                    }
                } else {
                    if (TextUtils.isEmpty(etCaptcha.getText())) {
                        etCaptcha.setError("不能为空");
                        return;
                    }
                    if (TextUtils.isEmpty(etAccount.getText())) {
                        etAccount.setError("不能为空");
                        return;
                    }
                    if (Canstants.STATE_REGISTER == type)
                        mUserId = etAccount.getText().toString();
                    else
                        mUserId = UserPreferences.getUserId();
                    obtainView().doVerify(mUserId, etPhone.getText().toString(), etCaptcha.getText().toString());
                }

            }
        });
        setOnBackListener(0, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Canstants.STATE_REGISTER == type && COMPLETE.equals(getToolbarRightTv().getText().toString())) {
                    getToolbarRightTv().setText(NEXT_STEP);
                    llOneStep.setVisibility(View.VISIBLE);
                    llTwoStep.setVisibility(View.GONE);
                } else {
                    finish();
                }
            }
        });
        cbIsOpen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
        cbIsOpen2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    etPasswordAgain.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    etPasswordAgain.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
        tvCaptcha.setOnCaptchaListener(new DownTimeTextView.OnCaptchaListener() {
            @Override
            public boolean onClick(View v) {
                if (TextUtils.isEmpty(etPhone.getText())) {
                    etPhone.setError("不能为空");
                    return false;
                } else if (!ValidateUtils.Mobile(etPhone.getText().toString())) {
                    etPhone.setError("不是有效号码");
                    return false;
                }
                obtainView().doGetVerificationCode(etPhone.getText().toString());
                return true;
            }
        });
    }

    /**
     * @param context
     * @param type    Canstants.STATE_REGISTER, Canstants.STATE_FIND_PASSWORD
     */
    public static void jumpTo(Context context, int type) {
        Intent intent = new Intent(context, ForgetPasswordActivity.class);
        intent.putExtra(Canstants.KEY_REGISTER_OR_FIND_PSD, type);
        context.startActivity(intent);
    }

    public static void jumpToForResult(Activity context, int type) {
        Intent intent = new Intent(context, ForgetPasswordActivity.class);
        intent.putExtra(Canstants.KEY_REGISTER_OR_FIND_PSD, type);
        context.startActivityForResult(intent, 100);
    }

    @Override
    protected ForgetPasswordView bindNettyMessageView() {
        return new ForgetPasswordView(this);
    }

    @Override
    public void onVerifyCodeCallback(int code, String msg) {
        if (IMSContacts.ResponseCode.SUCCESS != code) {
            tvCaptcha.reset();
            JToast.showShort(ForgetPasswordActivity.this, msg);
            return;
        }
        JToast.showShort(ForgetPasswordActivity.this, "手机验证码发送成功！");
    }

    @Override
    public void onVerifyCallback(int code, String msg) {
        if (IMSContacts.ResponseCode.SUCCESS != code) {
            if (TextUtils.isEmpty(msg)) msg = "手机验证失败";
            JToast.showShort(ForgetPasswordActivity.this, msg);
            return;
        }
        getToolbarRightTv().setText(COMPLETE);
        llOneStep.setVisibility(View.GONE);
        llTwoStep.setVisibility(View.VISIBLE);
    }

    @Override
    public void onResetCallback(int code, String msg) {
        if (IMSContacts.ResponseCode.SUCCESS != code) {
            if (TextUtils.isEmpty(msg)) msg = "密码重置失败";
            JToast.showShort(ForgetPasswordActivity.this, msg);
            return;
        }

        RectButtonHintDialog dialog = new RectButtonHintDialog(this)
                .setTitle("账号安全")
                .setContent("请您牢记密码，无痕密码不可逆")
                .setSubmit("知道了", v -> finishForResult());
        dialog.setOnDismissListener(alert -> finishForResult());
        dialog.show();
    }

    public void finishForResult() {
        UserTableBean user = UserTableBean.queryUserById(IMSContacts.UserType.REGISTERED_USER, mUserId);
        if (null != user) {
            String password = DES.encode(etPassword.getText().toString());
            user.setSecret(password);
            DbController.getInstance().getWrite().update(user);
        }
        if (Canstants.STATE_REGISTER == type) {
            setResult(Canstants.REQUEST_CODE_BACK);
        } else {
            setResult(100);
        }
        finish();
    }
}
